/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import cn.webrx.config.AppConfig;
import cn.webrx.entity.Book;
import cn.webrx.entity.Country;
import cn.webrx.entity.Menu;
import cn.webrx.entity.Student;
import cn.webrx.entity.User;
import cn.webrx.entity.Users;
import cn.webrx.interceptor.MyPager;
import cn.webrx.mapper.AdminMapper;
import cn.webrx.mapper.BookMapper;
import cn.webrx.mapper.CountryMapper;
import cn.webrx.mapper.DbMapper;
import cn.webrx.mapper.MenuMapper;
import cn.webrx.mapper.StuMapper;
import cn.webrx.mapper.StudentMapper;
import cn.webrx.mapper.UserMapper;
import cn.webrx.mapper.UsersMapper;
import cn.webrx.utils.SnowFlakeUtils;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.SpringVersion;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import tk.mybatis.mapper.entity.Example;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p></p>
 * <p>Powered by webrx On 2023-04-19 14:17:15</p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@SpringJUnitConfig(AppConfig.class)
public class MybatisDemo {
    @Autowired
    ApplicationContext ctx;

    @Autowired
    DruidDataSource ds;

    @Autowired
    SqlSession ss;

    @Autowired
    DbMapper dm;

    @Autowired
    BookMapper bm;

    @Test
    void m29(){

        //BookMapper bookm = ss.getMapper(BookMapper.class);
        //bookm.list();
        //ss.clearCache();
        //bookm.list();
        //bookm.list();
        //bookm.queryById(1033);

        bm.list();
        bm.list();
        bm.list();
        bm.list();
        bm.queryById(1033);
        bm.queryById(1033);
        bm.queryById(1033);
    }

    @Autowired
    StudentMapper sm;

    @Autowired
    StuMapper sum;

    @Autowired
    SnowFlakeUtils su;

    @Autowired
    CountryMapper cm;

    @Autowired
    AdminMapper am;

    @Autowired
    UserMapper um;

    @Autowired
    MenuMapper mm;


    @Autowired
    UsersMapper usm;

    @Test
    void m28(){
        List<Users> users = usm.queryAll();
        for(Users u : users){
            System.out.println(u.getId());
            System.out.println(u.getPassword());
            System.out.println(u.getAccount());
            System.out.println(u.getRoles());
        }
    }


    @Test
    void m27(){
        @Data @AllArgsConstructor
        class Users{
            private int id;
            private String name;
        }

        Set<Users> us = new HashSet<>();
        us.add(new Users(1,"jack"));
        us.add(new Users(1,"jack"));
        us.add(new Users(1,"jack"));
        System.out.println(us.size());

    }


    @Test
    void m26(){
        List<Menu> menus = mm.showMenu(1);
        System.out.println("---------------------");


        showmenu(menus,"");

        //for (Menu menu : menus) {
        //    System.out.println(menu.getName());
        //    System.out.println("=============================");
        //    for(Menu sub : menu.getSubmenu()){
        //        System.out.println(sub.getName());
        //        System.out.println("******");
        //        System.out.println(sub.getName());
        //    }
        //}
    }

    void showmenu(List<Menu> ms,String menuheader){
        for(Menu m : ms){
            System.out.println(menuheader+m.getName());
            System.out.println("-----------------");
            if(m.getSubmenu().size()>0) showmenu(m.getSubmenu(),menuheader+"      ");
        }
    }


    @Test @DisplayName("测试一对一关联查询")
    void m25(){
        List<User> us = um.queryAll();
        System.out.println(us);
        System.out.println("================================================");
        User user = um.show("admin");
        System.out.println("================================================");
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getUserAddress().stream().filter(e->e.isState()).findFirst().get().getName());
        System.out.println(user.getUserAddress().stream().filter(e->e.isState()).findFirst().get().getAddress());
        System.out.println(user.getUserAddress().stream().filter(e->e.isState()).findFirst().get().getPhone());
        System.out.println("================================================");
        System.out.println(user.getUserInfo().getTruename());
        //System.out.println(user.getUserAddress().stream().filter(a->a.isState()).findFirst().get());
    }


    @Test
    void m24(){
        //System.out.println(bm.pshow());
        Map<String,Object> map = new HashMap<>();
        bm.pcount(map);
        //System.out.println(map.get("count"));
        System.out.println(map);
        System.out.println(map.get("id"));
    }

    @Test
    void m23(){
        Map<String, Object> map = new HashMap<>();
        //map.put("id",1035);
        map.put("ids",List.of(915,1034,10,20,30,24,12));
        bm.delBy(map);


    }



    @Test
    void m22(){
        Map<String, Object> map = new HashMap<>();
        map.put("id",1035);
        map.put("name","mybaits1035");
        map.put("price",56);
        bm.mysave(map);
    }

    @Test
    void m21() {
        bm.querys();
        Map<String, Object> map = new HashMap<>();
        map.put("price",55);
        map.put("name", "%java%");
        bm.querys(map);
    }


    @Test
    void m20() {
        bm.queryAll();
        bm.queryAll(null);
        Map<String, Object> map = new HashMap<>();
        //map.put("id",90);
        //map.put("price",45);
        //map.put("maxprice",45);
        map.put("minprice", 25);
        bm.queryAll(map);
    }


    @Test
    void m19() {
        //Book book = new Book();
        //book.setId(10L);
        //book.setPrice(55);
        //book.setName("《my code》");

        //Book book = bm.queryById(10);
        //book.setPrice(99);
        //book.setName("myjava程序");
        //bm.myupdate(book);

        Map<String, Object> map = new HashMap<>();
        //map.put("id",10);
        //map.put("name","aaaa");
        //map.put("prices","price-5");
        map.put("price", "35");
        bm.myup(map);

    }


    @Test
    void m18() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "《java入门教程》");
        map.put("id", 915);
        map.put("pdate", LocalDate.now());
        bm.myinsert(map);


    }

    @Test
    void m17() {
        Map<String, Object> map = new HashMap<>();
        //map.put("id",90);
        //List<Book> list = bm.selectAll(map);
        //System.out.println(list.size());
        //System.out.println(list.get(0));

        map.put("name", "%ja_a%");
        //List<Book> list = bm.selectAll();
        //List<Book> list = bm.selectAll(null);
        List<Book> list = bm.selectAll(map);
    }


    @Test
    void m16() {
        System.out.println(am.queryAll());
    }

    @Test
    void m15() {
        Country c = new Country();
        //c.setId(20);
        //c.setCountryname("中国");
        //c.setCountrycode("86");
        //cm.save(c);
        //cm.insert(c);
        //cm.insertSelective(c);

        List<Country> cs = cm.selectAll();
        System.out.println(cs);

        //Country c2 = cm.selectByPrimaryKey(20);
        //c2.setCountrycode("99");
        //cm.save(c2);
        //System.out.println(c2);

        cm.deleteByPrimaryKey(20);

        Map<String, Object> map = new HashMap<>();
        map.put("id", 20);
        map.put("countryname", "中国");

        Example ex = new Example(Country.class);
        ex.setCountProperty("中国");
        ex.setTableName("tt");
        ex.selectProperties("id", "countrycode");
        ex.or().andEqualTo("id", 20);
        System.out.println(cm.selectByExample(ex));
        //System.out.println(cm.selectByExample(null));


    }

    @Test
    void m14() {
        Book b = new Book();
        b.setId(234234L);
        b.setName("《myatis ORM》");
        b.setPrice(55D);
        b.setAuthor("李四");
        b.setPdate(LocalDate.of(2023, 5, 15));
        bm.add(b);
    }


    @Test
    void m13() {
        long n = 9223372036854775807L;
        System.out.println(Long.MAX_VALUE);
        System.out.println(su.nextId());
        System.out.println(su.nextId());
        System.out.println(su.nextId());
        System.out.println(su.nextId());
        for (String s : ctx.getBeanDefinitionNames()) {
            System.out.println(s);
        }
    }

    @Test
    void m12() {
        Book b = new Book();
        b.setId(234234L);
        b.setName("《myatis ORM》");
        b.setPrice(55D);
        b.setAuthor("李四");
        b.setPdate(LocalDate.of(2023, 5, 15));
        //bm.add(b);

        //bm.deleteById(97);

        //MyPager.startPage(1,5);
        MyPager.startPage(4);
        bm.myByPage();
        System.out.println(MyPager.pageInfo());
    }


    @Test
    void m11() {
        //MyPager.startPage(2);
        //MyPager.startPage(2,5);
        List<Book> list = bm.myByPage();
        System.out.println(list);
    }


    @Test
    void m10() {
        bm.save("《数据库》", 50, "李强");
    }


    @Test
    void m9() {
        //使用分页插件
        //PageHelper.startPage(2,5);
        //PageHelper.startPage(2,5,"id desc,name asc");
        int currpage = 30;
        int pagesize = 20;


        //PageHelper.startPage(currpage,pagesize,"name asc");
        //PageHelper.startPage(currpage,pagesize,true,true,true);
        PageHelper.startPage(currpage, pagesize, true, true, false);
        //List<Book> data = bm.query();
        PageInfo<Book> pp = PageInfo.of(bm.query());
        //System.out.println(pp.getList());
        System.out.println(pp.getPageNum());//当前页 2
        System.out.println(pp.getPages());//共有多少页 7
        System.out.println(pp.getPageSize());//每页多少条 3
        System.out.println(pp.getTotal());//总记录数 总条数 19
        List<Book> list = pp.getList();//获取当前页的数据
        for (Book b : list) {
            System.out.println(b);
        }
    }


    @Test
    void m8() {
        int recordcount = bm.count();
        System.out.println(recordcount);
        int pagesize = 5;
        System.out.println(pagesize);
        int pagecount = recordcount % pagesize == 0 ? recordcount / pagesize : recordcount / pagesize + 1;
        System.out.println(pagecount);

        int currpage = 2;
        if (currpage < 1) currpage = 1;
        if (currpage > pagecount) currpage = pagecount;


        Map<String, Object> map = new HashMap<>();
        map.put("start", currpage * pagesize - pagesize);
        map.put("size", pagesize);
        List<Book> list = bm.page(map);
        System.out.println(list);

        System.out.println("==============================");

        //是mybatis内置分页功能，不推荐使用
        RowBounds rows = new RowBounds(currpage * pagesize - pagesize, pagesize);
        System.out.println(bm.pages(null, rows));

        System.out.println("==============================");

    }


    @Test
    void m7() {


        Student ss = sum.getStu(3);
        try {
            FileOutputStream fos = new FileOutputStream("c:/my.png");
            for (byte b : ss.getPhoto()) {
                fos.write(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println();
    }

    @Test
    void m6() {
        Student st = new Student();
        st.setName("cat");
        st.setStu(true);
        st.setMoney(50D);
        try (FileInputStream fis = new FileInputStream("c:/12.png")) {
            //st.setPhoto(fis.readAllBytes());
            byte[] buf = new byte[1024];
            List<Byte> all = new ArrayList<>();
            int len = -1;
            while ((len = fis.read(buf)) > 0) {
                for (int i = 0; i < len; i++) {
                    all.add(buf[i]);
                }
            }
            Byte[] temp = new Byte[all.size()];
            all.toArray(temp);
            st.setPhoto(temp);


        } catch (Exception e) {
        }
        int rows = sum.add(st);
        System.out.println(rows);

    }


    @Test
    void m5() {
        //dm.delTable("mytt");
        //dm.createTable("create table if not exists mytt(id int,name varchar(30))");
        //System.out.println(dm.tbs());

        //System.out.println(ss.selectList("cn.webrx.mapper.DbMapper.show"));
        //ss.delete("del",9);
        //System.out.println(bm.show());;

        //bm.deleteById(2424);
        //System.out.println(bm.show());

        bm.deleteByName("%aaa%");

    }


    @Test
    void m4() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三丰");
        map.put("score", 99);
        map.put("money", 1000);
        map.put("birth", LocalDate.of(1985, 10, 20));
        map.put("time", LocalDateTime.now());

        int rows = sm.add(map);
        System.out.println(rows);

        System.out.println(dm.list("t_stu", "*", "where 1"));
    }


    @Test
    void m3() {
        //System.out.println(dm.list("mysql.user","user,plugin,host"));

        System.out.println(dm.list("mysql.user", "host,user,plugin,@@version,@@port,user()", "where host='%'"));

        //System.out.println(dm.list("t_book","name,author,price","where price > 30"));

        //System.out.println(dm.count("t_book"));
        //System.out.println(dm.count("mysql.user"));
    }


    @Test
    @DisplayName("查询书籍表测试")
    void book1() {
        //System.out.println(bm.queryById(73));
        //System.out.println(bm.list());
        //System.out.println(bm.show());
        Book b = new Book();
        b.setName("《myatis ORM》");
        b.setPrice(55D);
        b.setAuthor("李四");
        b.setPdate(LocalDate.of(2023, 5, 15));
        //System.out.println(bm.add(b));
        //System.out.println(b);

        //System.out.println(bm.add(b));

        //System.out.println(bm.save("《db2》",50,"王五"));

        Map<String, Object> map = new HashMap<>();
        map.put("name", "《vue入门》");
        map.put("author", "李强");
        map.put("price", 66);

        System.out.println(map);
        int n = bm.insert(map);
        System.out.println(n);
        System.out.println(map);


    }

    @Test
    void query() {
        System.out.println(bm.show());
    }


    @Test
    void m2() {
        System.out.println(dm.dbInfo());
        System.out.println(dm.tbs());
    }


    @Test
    void m1() throws SQLException {
        Connection conn = ds.getConnection();
        System.out.println(conn.getMetaData().getDatabaseProductVersion());

        //mybatis jdbc 接口
        //System.out.println(ss.getConnection());
        //Connection co = ss.getConnection();
    }


    @Test
    void show() {
        System.out.println(SpringVersion.getVersion());
        System.out.println(ctx.getBeanDefinitionCount());
        for (String n : ctx.getBeanDefinitionNames()) {
            System.out.println(n);
        }

        System.out.println(ctx.getBean("now", LocalDate.class));
    }
}
